/* eslint-disable @typescript-eslint/indent */
import * as File from './file'
import { success, fail } from './types'
import { Router } from 'express'

const router = Router()

router.get('/:filename/*', (req, res) => {
    // check
    const _ = req.params
    if (!_.filename || _.filename.match(/[^A-Za-z0-9-\_\@\/]+/))
        res.send(fail('Invalid xpath.'))
    else {
        const file = File.getCustom(_.filename)
        let x = file
        if (!_[0])
            res.send(success(file))
        else {
            const xpath = _[0].split('/')
            try {
                xpath.forEach(key => {
                    if (!isNaN(key))
                        x = x[parseInt(key)]
                    else if (key == "keys")
                        x = Object.keys(x)
                    else if (x.hasOwnProperty(key))
                        x = x[key]
                    else
                        throw(`Invalid xpath: ${xpath}`)
                })
            } catch (e) {
                res.send(fail(`Error: ${e}`))
                return
            }
            res.send(success(x))
        }
    }
})

export default router
